package com.jy.api.service.impl;

import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.UserDao;
import com.jy.api.domain.Employee;
import com.jy.api.domain.User;
import com.jy.api.service.UserService;
import com.jy.api.signUpReq.admin.UserSignUpReq;
import com.jy.api.util.BCryptUtils;
import com.jy.api.util.UuidUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    UserDao userDao;


    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Transactional
    public void addUser(UserSignUpReq userOrder) {
        User user = new User(UuidUtil.getUuid(),
                userOrder.getUsername(), BCryptUtils.encrypt(userOrder.getPassword()));
        userDao.save(user);
    }


    /**
     * 用户权限
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByUsername(username);
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();

        List<Employee> employees = employeeDao.findByUsernameAndEnabled(username, true);

        for(Employee employee: employees){
            //店员登陆权限
            if (employee != null) {
                JSONArray jsonArray = JSONArray.fromObject(employee.getGroup().getRoles());
                for (Object o : jsonArray) {
                    simpleGrantedAuthorities.add(new SimpleGrantedAuthority(o.toString()));
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(
                username, user.getPassword(), simpleGrantedAuthorities);
    }


    @Override
    public void addUser(User user, String roles) {
        user.setPassword(BCryptUtils.encrypt(user.getPassword()));
        User user1 = userDao.findByUsername(user.getUsername());
        if (user1 == null) {
            user.setId(UuidUtil.getUuid());
            userDao.save(user);
        } else {
            user1.setName(user.getName());
            user1.setUsername(user.getUsername());
        }

    }
}
